from leapp.actors import Actor
from leapp.libraries.common.rpms import has_package
from leapp.models import InstalledRedHatSignedRPM
from leapp.reporting import Report, create_report
from leapp import reporting
from leapp.tags import ChecksPhaseTag, IPUWorkflowTag
from leapp.libraries.stdlib import run


class CheckPackagesForUpgrade(Actor):
    """
    Check version of some packages that may have impact on upgrade process
    """

    name = 'checkpkgforupgrade'
    consumes = (InstalledRedHatSignedRPM,)
    produces = (Report,)
    tags = (ChecksPhaseTag, IPUWorkflowTag)

    def get_releasever_of_rpm(self, pkg_name):
        rel_ver = run(['rpm', '-q', pkg_name, '--qf', '%{RELEASE}'], split=False)['stdout']
        return rel_ver

    def compare_version(self, ver1, ver2):
        """
        ver1 < ver2, return -1
        ver1 = ver2, return 0
        ver1 > ver2, return 1
        """
        list1 = str(ver1).split(".")
        list2 = str(ver2).split(".")
        if len(list1) > len(list2):
            length = len(list2)
        else:
            length = len(list1)

        for i in range(0, length):
            if list1[i] > list2[i]:
                return 1
            elif list1[i] < list2[i]:
                return -1
        if len(list1) > len(list2):
            return 1
        elif len(list1) < len(list2):
            return -1
        else:
            return 0


    def process(self):
        if has_package(InstalledRedHatSignedRPM, 'grub2'):
            grub2_version = self.get_releasever_of_rpm('grub2')
            if self.compare_version(grub2_version, '0.64') < 0:
                commands = [['yum', '-y', 'update', 'grub2']]
                create_report([
                    reporting.Title('grub2 version is too low for system upgrade'),
                    reporting.Summary(
                        'grub2 version must be upgrade to version >= 2.02-0.64, '
                        'otherwise system upgrade will get failed after reboot.'
                    ),
                    reporting.Severity(reporting.Severity.HIGH),
                    reporting.Flags([reporting.Flags.INHIBITOR]),
                    reporting.Remediation(commands=commands),
                    reporting.RelatedResource('package', 'grub2'),
                ]) 
